package com.pengcheng.taskapplication.mvp.view.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.pengcheng.taskapplication.R;
import com.pengcheng.taskapplication.adapter.LisenceAdapter;
import com.pengcheng.taskapplication.contants.ConstantValue;
import com.pengcheng.taskapplication.helper.ImageLoader;
import com.pengcheng.taskapplication.model.BannerModel;
import com.pengcheng.taskapplication.model.CarSignModel;
import com.pengcheng.taskapplication.model.NoticeModel;
import com.pengcheng.taskapplication.model.SubscribeOrderListModel;
import com.pengcheng.taskapplication.mvp.presenter.UserPresenter;
import com.pengcheng.taskapplication.mvp.presenter.UserPresenterV2;
import com.pengcheng.taskapplication.mvp.view.activity.ActivityBiaoShi;
import com.pengcheng.taskapplication.mvp.view.activity.ApplySuccessActivity;
import com.pengcheng.taskapplication.mvp.view.activity.CarSignAndUnSign;
import com.pengcheng.taskapplication.mvp.view.activity.Html5Activity;
import com.pengcheng.taskapplication.mvp.view.activity.Html5AgressActivity;
import com.pengcheng.taskapplication.mvp.view.activity.IndexTestActivity;
import com.pengcheng.taskapplication.mvp.view.activity.MainActivity;
import com.pengcheng.taskapplication.mvp.view.activity.MyApplyAndCarsList;
import com.pengcheng.taskapplication.mvp.view.activity.MyCarList;
import com.pengcheng.taskapplication.mvp.view.activity.MyCarListGuanjia;
import com.pengcheng.taskapplication.mvp.view.activity.MyInfo;
import com.pengcheng.taskapplication.mvp.view.activity.NoticeDetailActivity;
import com.pengcheng.taskapplication.mvp.view.activity.ParkScanActivity;
import com.pengcheng.taskapplication.mvp.view.activity.ParkWashActivity;
import com.pengcheng.taskapplication.mvp.view.activity.QrScanActivity;
import com.pengcheng.taskapplication.mvp.view.activity.SearchActivity;
import com.pengcheng.taskapplication.mvp.view.activity.UploadIdCard;
import com.pengcheng.taskapplication.mvp.view.widget.MarqueeTextView;
import com.pengcheng.taskapplication.mvp.view.widget.MarqueeTextViewClickListener;
import com.pengcheng.taskapplication.mvp.view.widget.MyListView;
import com.pengcheng.taskapplication.net.ConvertUtil;
import com.pengcheng.taskapplication.net.IView;
import com.pengcheng.taskapplication.rxbus.RxBusRoute;
import com.pengcheng.taskapplication.rxbus.RxEvent;
import com.pengcheng.taskapplication.util.SPUtils;
import com.pengcheng.taskapplication.util.ToastUtils;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class IndexFragment extends BaseFragment implements IView {


    private String token;
    private String newtoken;
    private String uid;
    private UserPresenter userPresenter;
    private UserPresenterV2 userPresenterV2;
    private static final int REQUEST_CODE = 121;
    private String washid = "";
    private String deviceid = "";

    ArrayList<CarSignModel> carSignModels= new ArrayList<>();

    @BindView(R.id.top_banner)
    MZBannerView topZannerView;

    @BindView(R.id.rl_top)
    RelativeLayout rl_top;

    @BindView(R.id.tv_notice)
    MarqueeTextView marqueeTextView;


    private int page=0;
    private int pagesize=10;


    @Override
    protected int layoutResID() {
        return R.layout.fragment_index_layout;
    }

    @Override
    protected void initData() {
        token = SPUtils.getString(context, ConstantValue.SpType.token);
        uid = SPUtils.getString(context, ConstantValue.SpType.userid);
        newtoken = SPUtils.getString(context, ConstantValue.SpType.newtoken);
        userPresenter = new UserPresenter(this);
        userPresenterV2 = new UserPresenterV2(this);
        getSignCars(newtoken,uid);
        queryNotice(newtoken,uid,page,pagesize);
    }

    public void getSubscribes(int page, int pageSize) {
        userPresenter.getSubscribes(page, pageSize, ConstantValue.RequestKey.getSubscribes);
    }

    public void queryNotice(String token,String uid,int page,int pagesize){
        userPresenterV2.getNotcieList(token,uid,page,pagesize,ConstantValue.RequestKey.queryNotice);
    }

    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        if (actionType.equals(ConstantValue.RequestKey.getSubscribes)) {

        }

        if(actionType.equals(ConstantValue.RequestKey.queryNotice)){
            Gson gson= new Gson();
            Type type =new TypeToken<ArrayList<NoticeModel>>(){}.getType();
            ArrayList<NoticeModel> orderModels= gson.fromJson(gson.toJson(data),type);


            marqueeTextView.setTextArraysAndClickListener(orderModels, new MarqueeTextViewClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(context, NoticeDetailActivity.class);
                    intent.putExtra("model",(NoticeModel)view.getTag());
                    startActivity(intent);
                }
            });
        }

        if(actionType.equals(ConstantValue.RequestKey.getSignCars)){
            carSignModels.clear();
            carSignModels.addAll((ArrayList<CarSignModel>)data);
            if(carSignModels.size()!=0){
                rl_top.setVisibility(View.GONE);

                CarSignModel carSignModel =new CarSignModel();
                carSignModel.setVehicle_id("-1");
                carSignModels.add(carSignModel);
                setTopBanner(carSignModels);
                topZannerView.setVisibility(View.VISIBLE);
            }else{
                rl_top.setVisibility(View.VISIBLE);
                topZannerView.setVisibility(View.GONE);
            }

        }
    }

    @Override
    public void onFailed(String code, String msg) {
    }


    private void setTopBanner(ArrayList<CarSignModel> carSignModels) {

        topZannerView.addPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //Log.e("zw","onPageScrolled---->"+position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        topZannerView.setPages(carSignModels, new MZHolderCreator<TopBannerViewHolder>() {
            @Override
            public TopBannerViewHolder createViewHolder() {
                return new TopBannerViewHolder();
            }
        });
        topZannerView.start();
        topZannerView.setIndicatorVisible(false);

    }

    public class TopBannerViewHolder implements MZViewHolder<CarSignModel> {
        private TextView tv_car_num;
        private TextView tv_e_car_num;
        private RelativeLayout rl_top;

        private LinearLayout ll_detail;

        private TextView tv_add_card;


        @Override
        public View createView(Context context) {
            View view = LayoutInflater.from(context).inflate(R.layout.activity_car_list_sign_item_layout, null);
            tv_car_num = (TextView) view.findViewById(R.id.tv_car_num);
            tv_e_car_num = (TextView) view.findViewById(R.id.tv_e_car_num);

            ll_detail=(LinearLayout) view.findViewById(R.id.ll_detail);
            tv_add_card=(TextView)view.findViewById(R.id.tv_add_card);
            rl_top=(RelativeLayout)view.findViewById(R.id.rl_top);
            rl_top.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CarSignModel model=(CarSignModel) v.getTag();
                    if(model.getVehicle_id().equals("-1")){
                        boolean isreal2=SPUtils.getBoolean(context, ConstantValue.SpType.isreal);
                        if(isreal2) {
                            Intent intent = new Intent(context, Html5AgressActivity.class);
                            intent.putExtra("url", "file:///android_asset/instructions.html");
                            intent.putExtra("title", "办理须知");
                            startActivity(intent);
                        }else{
                            Intent  intent = new Intent(context, UploadIdCard.class);
                            startActivity(intent);
                        }
                    }else {
                        Intent intent =new Intent(context, ActivityBiaoShi.class);
                        intent.putExtra("model",model);
                        startActivity(intent);
                    }
                }
            });
            return view;
        }

        @Override
        public void onBind(Context context, int i, CarSignModel carSignModel) {
            Log.e("zhouwei", "current position:" + i);

            if(carSignModel.getVehicle_id().equals("-1")){
                ll_detail.setVisibility(View.GONE);
                tv_add_card.setVisibility(View.VISIBLE);
                tv_e_car_num.setText("立即添加电子车牌标识");
                tv_car_num.setText("暂无车辆信息");
                rl_top.setTag(carSignModel);
            }else {
                ll_detail.setVisibility(View.VISIBLE);
                tv_add_card.setVisibility(View.GONE);
                tv_e_car_num.setText(carSignModel.getEcard_code());
                tv_car_num.setText(carSignModel.getPlate_no());
                rl_top.setTag(carSignModel);
            }

        }
    }



    @OnClick({R.id.ll_dianzhi,R.id.ll_right,R.id.rl_top,R.id.ll_scan,R.id.ll_anzhuang,R.id.ll_xiche,R.id.ll_tingche,R.id.ll_top1,R.id.ll_top2,R.id.ll_top3,R.id.rl_search})
    public void onViewClicked(View view) {
        Intent intent ;
        switch (view.getId()) {
            //扫一扫
            case R.id.ll_scan:
                AndPermission.with(this)
                        .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                        .onGranted(new Action() {
                            @Override
                            public void onAction(List<String> permissions) {
                                Intent intent = new Intent(context, QrScanActivity.class);
                                startActivityForResult(intent, REQUEST_CODE);
                            }
                        })
                        .onDenied(new Action() {
                            @Override
                            public void onAction(List<String> permissions) {
                                Uri packageURI = Uri.parse("package:" + getActivity().getPackageName());
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                Toast.makeText(context, "没有权限", Toast.LENGTH_LONG).show();
                            }
                        }).start();
                break;
            //安装
            case R.id.ll_anzhuang:
                boolean isreal=SPUtils.getBoolean(context, ConstantValue.SpType.isreal);

                if(isreal) {
                    intent = new Intent(context, Html5AgressActivity.class);
                    intent.putExtra("url", "file:///android_asset/instructions.html");
                    intent.putExtra("title", "办理须知");
                    startActivity(intent);
                }else{
                    intent = new Intent(context, UploadIdCard.class);
                    startActivity(intent);
                }
                break;
            //洗车
            case R.id.ll_xiche:
                intent = new Intent(context, ParkWashActivity.class);
                startActivity(intent);
                break;
            //停车
            case R.id.ll_tingche:
                intent = new Intent(context, ParkScanActivity.class);
                startActivity(intent);
                break;
            //车辆管家
            case R.id.ll_top1:
                intent = new Intent(context, MyCarListGuanjia.class);
                startActivity(intent);
                break;
            //年检标
            case R.id.ll_top2:
                intent = new Intent(context, MyCarList.class);
                intent.putExtra("type","1");
                startActivity(intent);
                break;
            //行驶证
            case R.id.ll_top3:
                 intent = new Intent(context, MyCarList.class);
                 intent.putExtra("type","2");
                 startActivity(intent);
                break;
             //办理电子车牌
            case R.id.rl_top:
                boolean isreal1=SPUtils.getBoolean(context, ConstantValue.SpType.isreal);

                if(isreal1) {
                    intent = new Intent(context, Html5AgressActivity.class);
                    intent.putExtra("url", "file:///android_asset/instructions.html");
                    intent.putExtra("title", "办理须知");
                    startActivity(intent);
                }else{
                    intent = new Intent(context, UploadIdCard.class);
                    startActivity(intent);
                }
                break;
            //办理电子车牌
            case R.id.ll_dianzhi:
                boolean isreal2=SPUtils.getBoolean(context, ConstantValue.SpType.isreal);
                if(isreal2) {
                    intent = new Intent(context, Html5AgressActivity.class);
                    intent.putExtra("url", "file:///android_asset/instructions.html");
                    intent.putExtra("title", "办理须知");
                    startActivity(intent);
                }else{
                    intent = new Intent(context, UploadIdCard.class);
                    startActivity(intent);
                }
                break;


            case R.id.tv_notice:
//                intent = new Intent(context, Html5AgressActivity.class);
//                intent.putExtra("url","file:///android_asset/instructions.html");
//                intent.putExtra("title","办理须知");
//                startActivity(intent);
                break;
            case R.id.ll_right:
                ((MainActivity)getActivity()).goRecommend(1);
                break;
            case R.id.rl_search:
                intent =new Intent(context, SearchActivity.class);
                startActivity(intent);
                break;





        }
    }

    @Override
    protected boolean isRegistRxBus() {
        return true;
    }

    /**
     * 注册订阅事件
     */
    protected void receiveEvent(RxEvent rxEvent) {
        switch (rxEvent.busName) {
            case RxBusRoute.REFRESH:
                break;

            case RxBusRoute.indexfresh:
                getSignCars(newtoken,uid);
                queryNotice(newtoken,uid,page,pagesize);
                break;

        }



    }

    @SuppressWarnings("unchecked")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    //如果是url 跳转到http 页面
                    if (ConvertUtil.isHttpUrl(result)) {
                        Intent intent = new Intent(context, Html5Activity.class);
                        intent.putExtra("url", result);
                        startActivity(intent);
                    } else {
                        //如果是扫码的洗车或者停车二维码
                        if (ConvertUtil.validate(result)) {
                            try {
                                JsonObject jsonObject = (JsonObject) new JsonParser().parse(result).getAsJsonObject();
                                String type = jsonObject.get("type").getAsString();
                                if (type.equals("parkIn")) {
                                    //获取停车场的id 和通道
                                    String parkid = jsonObject.get("parkid").getAsString();
                                    String laneno = jsonObject.get("laneno").getAsString();
                                    //进入通道
                                    inPark(newtoken, uid, parkid, laneno);
                                } else if (type.equals("parkExit")) {
                                    //获取停车场的id 和通道
                                    String parkid = jsonObject.get("parkid").getAsString();
                                    String laneno = jsonObject.get("laneno").getAsString();
                                    //进入通道
                                    outPark(newtoken, uid, parkid, laneno);
                                } else if (type.equals("wash")) {
                                    //获取停车场的id
                                    washid = jsonObject.get("washid").getAsString();
                                    deviceid = jsonObject.get("deviceid").getAsString();
                                    //解析成功后，扫出码中信息，然后弹窗,缓存下
                                    //扫码出设备id需要判断设备准备好
                                    geDeviceStatus(newtoken, uid, deviceid);
                                    //showDialog(washTypeModelArrayList);
                                }
                            } catch (Exception e) {
                                ToastUtils.showShortToast("请扫码正确的二维码");
                            }
                        }
                    }
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(context, "解析二维码失败,请重新扫码", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    public void inPark(String token, String uid, String parkid, String laneno) {
        userPresenterV2.commitOrder(token, uid, parkid, laneno, ConstantValue.RequestKey.inPark);
    }

    public void outPark(String token, String uid, String parkid, String laneno) {
        userPresenterV2.commitOrder(token, uid, parkid, laneno, ConstantValue.RequestKey.commitOrder);
    }
    public void geDeviceStatus(String token, String uid, String deviceid) {
        userPresenterV2.getStatus(token, uid, deviceid, ConstantValue.RequestKey.getDeviceStatus);
    }

    public void getSignCars(String token,String uid){
        userPresenterV2.getCarSignList(token,uid, ConstantValue.RequestKey.getSignCars);
    }

    @Override
    public void onResume() {
        super.onResume();
//        token = SPUtils.getString(context, ConstantValue.SpType.token);
//        uid = SPUtils.getString(context, ConstantValue.SpType.userid);
//        newtoken = SPUtils.getString(context, ConstantValue.SpType.newtoken);
        getSignCars(newtoken,uid);
    }

    @Override
    public void onDestroy() {
        if(marqueeTextView!=null) {
            marqueeTextView.releaseResources();
        }
        super.onDestroy();
    }
}
